package com.sky.aspect;

import com.fasterxml.jackson.databind.ser.Serializers;
import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.data.annotation.Version;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PutMapping;

import javax.swing.text.html.parser.Entity;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

/*
* 自定义切面类，实现公共字段填充
* */
@Aspect
@Component
@Slf4j
public class AutofillAspect {
    /*
    * 切入点
    * */
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void  autoFillPointCut(){}


    /*
    * 前置通知
    * */
    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint) throws Exception {
        log.info("开始进行公共字段的填充");
        //方法签名对象
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获得注解
        AutoFill annotation = signature.getMethod().getAnnotation(AutoFill.class);
        OperationType value = annotation.value();

        //获得方法参数
        Object [] args=joinPoint.getArgs();
        if(args==null||args.length==0){
            return;
        }
        Object o=args[0];

        //准备数据
        LocalDateTime ldt=LocalDateTime.now();
        Long id= BaseContext.getCurrentId();

        //根据操作类型来赋值
        if(value==OperationType.INSERT){
            Method setCreateTime = o.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
            Method setUpdateTime = o.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method setCreateUser = o.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
            Method setUpdateUser = o.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
            setCreateTime.invoke(o,ldt);
            setUpdateTime.invoke(o,ldt);
            setCreateUser.invoke(o,id);
            setUpdateUser.invoke(o,id);
        }else if(value==OperationType.UPDATE){
            Method setUpdateTime = o.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method setUpdateUser = o.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
            setUpdateTime.invoke(o,ldt);
            setUpdateUser.invoke(o,id);
        }


    }




}
